import router from "@/router";

export function parseJwt(token) {
  if (!token) {
    router.push('/login');
  }
    const parts = token.split('.');
    if (parts.length !== 3) {
      throw new Error('Invalid JWT format');
    }
  
    // 处理 Base64Url 转标准 Base64
    const base64ToBase64Url = (base64) => {
      return base64
        .replace(/-/g, '+')
        .replace(/_/g, '/')
        .padEnd(base64.length + (4 - (base64.length % 4)) % 4, '='); // 自动补全填充
    };
  
    // 解码 UTF-8
    const decodeBase64 = (base64) => {
      const binStr = atob(base64ToBase64Url(base64));
      const bytes = new Uint8Array(binStr.length);
      for (let i = 0; i < binStr.length; i++) {
        bytes[i] = binStr.charCodeAt(i);
      }
      return new TextDecoder().decode(bytes); // 现代浏览器方案
    };
  
    try {
      const header = JSON.parse(decodeBase64(parts[0]));
      const payload = JSON.parse(decodeBase64(parts[1]));
      return { header, payload };
    } catch (e) {
      throw new Error('JWT parsing failed: ' + e.message);
    }
  }